"""
Created on 202-04-10
@author:刘飞
@description:zip文件压缩和解压缩
"""

import os
import zipfile


# 压缩
def make_zip(source_dir, output_filename):
    """
    本方法可压缩文件夹或者单个文件
    :param source_dir: 木匾文件夹目录
    :param output_filename: 结果压缩文件名称
    :return:
    """
    zipf = zipfile.ZipFile(output_filename, 'w')
    if os.path.isdir(source_dir):  # 压缩文件夹
        pre_len = len(os.path.dirname(source_dir))
        print(f'pre_len:{pre_len}')
        for parent, dir_names, filenames in os.walk(source_dir):
            print(f'parent:{parent}, dir_names:{dir_names}, filenames:{filenames}')
            for filename in filenames:
                print(f'filename,{filename}')
                pathfile = os.path.join(parent, filename)
                print(f'pathfile:{pathfile}')
                arc_name = pathfile[pre_len:].strip(os.path.sep)  # 相对路径
                print(f'arc_name:{arc_name}')
                zipf.write(pathfile, arc_name)
    elif os.path.isfile(source_dir):  # 压缩单个文件
        zipf.write(source_dir, os.path.basename(source_dir))
    zipf.close()
    return 'Done'


# 解压缩
def un_zip(file_name):
    zip_file = zipfile.ZipFile(file_name)
    if os.path.isdir(file_name + '_files'):
        # 如果有目标文件夹 则跳过解压缩
        pass
    else:
        os.mkdir(file_name + '_files')
        for names in zip_file.namelist():
            zip_file.extract(names, file_name + '_files/')
    zip_file.close()


if __name__ == '__main__':
    make_zip('./my_own_images/2828_my_own_image.png', '2828.zip')
    un_zip('./2828.zip')
